package com.dc.web.controller;


import com.dc.constant.Constants;
import com.dc.constant.MessageConstant;
import com.dc.dao.ShipDao;
import com.dc.dao.ShipRepairDao;
import com.dc.dao.WorkflowShipWeldDao;
import com.dc.dao.WorkflowTowShipOilDao;
import com.dc.entity.ShipEntity;
import com.dc.entity.ShipRepairEntity;
import com.dc.entity.WorkflowShipWeldEntity;
import com.dc.entity.WorkflowTowShipOilEntity;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.WorkflowListBody;
import com.dc.service.CalibrationService;
import com.dc.service.dto.CalibrationShipWeldDto;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

@Api(tags = "2-单船工序-船体焊接")
@RequestMapping("/api/workflow_ship_weld")
@RestController
public class WorkflowShipWeldController {

    @Resource
    WorkflowShipWeldDao workflowShipWeldDao;

    @Resource
    ShipRepairDao shipRepairDao;

    @Resource
    ShipDao shipDao;

    @Resource
    CalibrationService calibrationService;

    @GetMapping("/list")
    public AjaxResult list(WorkflowListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Long repairId = body.getRepairId();     // 维修工单id

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(repairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        Page<WorkflowShipWeldEntity> resultList = workflowShipWeldDao.findByShipRepairEntity(shipRepairEntity, pageRequest);

        CalibrationShipWeldDto calibrationShipWeldDto = calibrationService.calcShipWeld();

        resultList.getContent().forEach(t -> {
            dynamicCalc(t, shipEntity, shipRepairEntity, calibrationShipWeldDto);
        });

        return AjaxResult.success(resultList);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<WorkflowShipWeldEntity> optional = workflowShipWeldDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowShipWeldEntity shipOilEntity = optional.get();

        ShipRepairEntity shipRepairEntity = shipOilEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);

        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        CalibrationShipWeldDto calibrationShipWeldDto = calibrationService.calcShipWeld();

        dynamicCalc(shipOilEntity, shipEntity, shipRepairEntity, calibrationShipWeldDto);

        return AjaxResult.success(shipOilEntity);
    }


    //  shipRepairId   weight   shipWeight    submit_time
    @PostMapping()
    public AjaxResult add(@RequestHeader HttpHeaders httpHeaders, @RequestBody WorkflowShipWeldEntity entity) {

        entity.setId(null);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowShipWeldEntity save = workflowShipWeldDao.save(entity);

        CalibrationShipWeldDto calibrationShipWeldDto = calibrationService.calcShipWeld();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationShipWeldDto);

        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody WorkflowShipWeldEntity entity) {

        entity.setId(id);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowShipWeldEntity save = workflowShipWeldDao.save(entity);

        CalibrationShipWeldDto calibrationShipWeldDto = calibrationService.calcShipWeld();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationShipWeldDto);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        workflowShipWeldDao.deleteById(id);

        return AjaxResult.success();
    }

    /**
     * 计算动态值
     * @param entity
     * @param shipEntity
     * @param shipRepairEntity
     */

    public static WorkflowShipWeldEntity dynamicCalc(WorkflowShipWeldEntity entity, ShipEntity shipEntity, ShipRepairEntity shipRepairEntity, CalibrationShipWeldDto calibrationShipWeldDto) {

        try {
            // 焊接总长(mm)  length * num
            Double totalLength = entity.getLength() * entity.getNum();
            entity.setTotalLength(totalLength);
        } catch (Exception e) {
            entity.setTotalLength(0.);
        }

        // 单位耗二氧化碳标定值
        Double co2ByUnit = calibrationShipWeldDto.getCo2ByUnit();

        try {
            // 单位耗二氧化碳标定值
            entity.setCo2ByUnit(co2ByUnit);
        } catch (Exception e) {
            entity.setCo2ByUnit(0.);
        }

        try {
            // 二氧化碳   weldType="船体焊接":  totalLength * 2 * co2ByUnit
            Double co2 = entity.getTotalLength() * 2 * co2ByUnit;
            if(Constants.WELD_TYPE_SHIP.equals(entity.getWeldType())) {
                entity.setCo2(co2);
            }
        } catch (Exception e) {
            entity.setCo2(0.);
        }

        // 单位耗电量标定值
        Double powerByUnit = calibrationShipWeldDto.getPowerByUnit();

        try {
            entity.setPowerByUnit(powerByUnit);
        } catch (Exception e) {
            entity.setPowerByUnit(0.);
        }

        try {
            // 耗电量   weldType="船体焊接":  totalLength * 2 * co2ByUnit
            Double power = entity.getTotalLength() * 2 * powerByUnit;
            if(Constants.WELD_TYPE_SHIP.equals(entity.getWeldType())) {
                entity.setPower(power);
            }
        } catch (Exception e) {
            entity.setPower(0.);
        }


        entity.setShipName(shipEntity.getName());
        entity.setReporter(shipRepairEntity.getUpdater());
        entity.setShipRepairId(shipRepairEntity.getId());
        return entity;
    }

}
